package com.itheima.shop.dao;

import com.itheima.shop.entity.Category;
import com.itheima.shop.entity.Product;
import com.itheima.shop.util.JdbcUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * 商品模块-持久层
 */
public class ProductDao {
    private QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());

    /**
     * 查询所有商品数量
     */
    public int getAllRecordNO(int cid) throws SQLException {
        String sql;
        Object[] params;
        if (cid==-1){
            sql = "select count(pid) from product";
            params=null;
        }else{
            sql = "select count(pid) from product where cid=?";
            params= new Object[]{cid};
        }
        Long temp = runner.query(sql, new ScalarHandler<>(), params);
        return temp.intValue();
    }
    /**
     * 通过商品编号查询商品,分页查询
     */
    public List<Map<String, Object>> findAllProductAjax( int start, int size) throws SQLException {
        String sql = "select * from  category c,product p where c.cid=p.cid limit ?,?";
        Object[] params = {start, size};
        return runner.query(sql, new MapListHandler(), params);
    }

    /**
     * 更新商品
     */
    public int updateProduct(Product product) throws SQLException {
        String sql = "update product set pname=?,market_price=?,shop_price=?,pimage=?,pdate=?,is_hot=?,pdesc=?,pflag=?,cid=? where pid=?";
        Object[] params = {product.getPname(),product.getMarket_price(),product.getShop_price(),product.getPimage(),product.getPdate(),
        product.getIs_hot(),product.getPdesc(),product.getPflag(),product.getCategory().getCid(),product.getPid()};
        return runner.update(sql, params);
    }

    /**
     * 增加商品
     */
    public int addProduct(Product product) throws SQLException {
        String sql = "insert into product (pname,market_price,shop_price,pimage,pdate,is_hot,pdesc,pflag,cid) values(?,?,?,?,?,?,?,?,?)";
        Object[] params = {product.getPname(),product.getMarket_price(),product.getShop_price(),product.getPimage(),product.getPdate(),
                product.getIs_hot(),product.getPdesc(),product.getPflag(),product.getCategory().getCid()};
        return runner.update(sql, params);
    }

    /**
     * 删除商品
     */
    public int deleteProduct(int pid) throws SQLException {
        String sql = "delete from product where pid = ?";
        Object[] params = {pid};
        return runner.update(sql, params);
    }
}

